package com.goodboys;

import com.alibaba.fastjson.JSON;
import com.goodboys.base.redis.JedisConfiguration;
import com.goodboys.bean.BaseParamBean;
import com.goodboys.service.IDataService;
import com.goodboys.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@SpringBootApplication
@EnableScheduling
@Import({JedisConfiguration.class, JedisUtil.class})
public class IDataApiApplication extends SpringBootServletInitializer {
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(IDataApiApplication.class);
	}
	public static void main(String[] args) {
		SpringApplication.run(IDataApiApplication.class, args);
	}

	@Autowired
	private IDataService iDataService;

	//每2小时更新内容到redis中
    @Scheduled(initialDelay= 1000,fixedDelay = 1000*60*60*2)
//    @Scheduled(initialDelay= 1000*100,fixedDelay = 1000*60*60)
	public void cron(){
	    System.out.println("-----------》开始定时刷热词到redis中");
        List<String> hotWords = iDataService.getHotWords();
        Map<String, String> result = new HashMap<>();
        Jedis jedis = JedisUtil.getJedis();
        //获取当前所有的hotWord
        Set<String> currHotWords = jedis.hkeys("hotWords");
        //设置关键字
        BaseParamBean param = new BaseParamBean();
        hotWords.stream().forEach( s -> {
            //判断关键字是够已经存在
            if(!currHotWords.contains(s)) {
                //获取关键字文章
                param.setKeyword(s);
                Map<String, Object> articleList = iDataService.getArticleList(param);
                if (!articleList.isEmpty()) result.put(s, JSON.toJSONString(articleList));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(result.get(s));
            }
        });
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!result.isEmpty())jedis.hmset("hotWords", result);
        if(jedis!=null){
            jedis.close();
             if(jedis.isConnected()) jedis.disconnect();
        }
        System.out.println("-----------》结束定时刷热词到redis中");
    }


}
